# -*- coding: utf-8 -*-
from PyQt6.QtWidgets import (QListWidget, QListWidgetItem, QFrame, QLabel, 
                           QVBoxLayout, QTableWidget, QTableWidgetItem, QHeaderView, QWidget)
from PyQt6.QtCore import Qt, QMimeData
from PyQt6.QtGui import QDrag, QFont

class DraggableListWidget(QListWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.setDefaultDropAction(Qt.DropAction.MoveAction)
    
    def startDrag(self, actions):
        item = self.currentItem()
        if item:
            mime_data = QMimeData()
            class_info = item.data(Qt.ItemDataRole.UserRole)
            # 将文本和二进制数据都设置到MIME数据中
            mime_data.setText(str(class_info))
            # 确保数据是bytes类型
            mime_data.setData("application/x-class-info", str(class_info).encode('utf-8'))
            
            drag = QDrag(self)
            drag.setMimeData(mime_data)
            drag.exec(Qt.DropAction.MoveAction)
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasText():
            event.accept()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        if event.mimeData().hasText():
            event.accept()
            class_info = event.mimeData().text()
            # 添加到未安排列表
            self.addItem(class_info)
            # 通知父窗口更新课表
            self.parent().parent().handle_class_return(class_info)

class ClassCell(QFrame):
    def __init__(self, class_info, parent=None):
        super().__init__(parent)
        self.class_info = class_info
        self.setAcceptDrops(True)
        self.init_ui()
    
    def init_ui(self):
        layout = QVBoxLayout()
        self.setLayout(layout)
        
        # 设置样式
        self.setStyleSheet("""
            ClassCell {
                background-color: #e3f2fd;
                border: 1px solid #90caf9;
                border-radius: 4px;
                margin: 2px;
                padding: 4px;
            }
            ClassCell:hover {
                background-color: #bbdefb;
                border: 1px solid #64b5f6;
            }
        """)
        
        # 显示班级信息
        info_label = QLabel(self.format_class_info())
        info_label.setWordWrap(True)
        info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(info_label)
    
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            # 创建拖拽
            drag = QDrag(self)
            mime_data = QMimeData()
            
            # 获取当前单元格的位置
            table = self.parent().parent()
            if isinstance(table, QTableWidget):
                row = table.row(self.parent())
                col = table.column(self.parent())
                # 保存源位置信息
                source_pos = (row, col)
                mime_data.setData("application/x-class-info", str((self.class_info, source_pos)).encode())
            
            mime_data.setText(str(self.class_info))
            drag.setMimeData(mime_data)
            
            # 开始拖拽
            drag.exec(Qt.DropAction.MoveAction)
            event.accept()
        else:
            super().mousePressEvent(event)
    
    def format_class_info(self):
        return "{}\n{}\n{}{}班\n男:{} 女:{}".format(
            self.class_info['college'],
            self.class_info['major'],
            self.class_info['grade'],
            self.class_info['class_name'],
            self.class_info['male'],
            self.class_info['female']
        )

class ScheduleCell(QTableWidgetItem):
    def __init__(self, text=""):
        super().__init__(text)
        self.setFlags(self.flags() | Qt.ItemFlag.ItemIsDropEnabled)
        self.classes = []  # 存储该时间段安排的班级信息
        self.widgets = []  # 存储显示的ClassCell部件
        self.setBackground(Qt.GlobalColor.white)
    
    def add_class(self, class_info):
        if class_info not in self.classes:
            self.classes.append(class_info)
            return True
        return False
    
    def remove_class(self, class_info):
        if class_info in self.classes:
            self.classes.remove(class_info)
            return True
        return False

class ScheduleTable(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(3, 5, parent)
        self.setAcceptDrops(True)
        self.verticalHeader().setDefaultSectionSize(120)
        self.horizontalHeader().setDefaultSectionSize(200)
        
        # 设置表头
        self.setHorizontalHeaderLabels(["星期一", "星期二", "星期三", "星期四", "星期五"])
        self.setVerticalHeaderLabels(["第1-2节", "第3-4节", "第5-6节"])
        
        # 设置表头字体
        header_font = QFont()
        header_font.setPointSize(10)
        header_font.setBold(True)
        self.horizontalHeader().setFont(header_font)
        self.verticalHeader().setFont(header_font)
        
        # 设置表格样式
        self.setStyleSheet("""
            QTableWidget {
                gridline-color: #cccccc;
                background-color: white;
            }
            QTableWidget::item {
                padding: 2px;
            }
            QHeaderView::section {
                background-color: #f0f0f0;
                padding: 4px;
                border: 1px solid #cccccc;
            }
        """)
        
        # 初始化单元格
        for row in range(self.rowCount()):
            for col in range(self.columnCount()):
                cell = ScheduleCell()
                self.setItem(row, col, cell)
        
        # 设置表格自动调整大小
        self.horizontalHeader().setStretchLastSection(True)
        self.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        self.verticalHeader().setSectionResizeMode(QHeaderView.ResizeMode.ResizeToContents)
    
    def dragEnterEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dragMoveEvent(self, event):
        if event.mimeData().hasText():
            event.acceptProposedAction()
        else:
            event.ignore()
    
    def dropEvent(self, event):
        if event.mimeData().hasText():
            pos = event.position().toPoint()
            item = self.itemAt(pos)
            if item:
                row = self.row(item)
                col = self.column(item)
                
                # 获取主窗口实例
                main_window = self.window()
                if hasattr(main_window, 'handle_class_drop'):
                    # 获取源位置信息（如果是从课表中拖动的）
                    source_data = event.mimeData().data("application/x-class-info")
                    if source_data:
                        try:
                            # 解析二进制数据为字符串，然后转换为Python对象
                            class_info_str = source_data.data().decode('utf-8')
                            class_info = eval(class_info_str)
                            
                            # 如果是元组，说明是从课表中拖动的（包含源位置信息）
                            if isinstance(class_info, tuple) and len(class_info) == 2:
                                class_data, source_pos = class_info
                                # 如果是同一个单元格，不处理
                                if (row, col) == source_pos:
                                    return
                                # 通知主窗口处理移动
                                main_window.handle_class_move(class_data, source_pos, row, col)
                                event.acceptProposedAction()
                                return
                            else:
                                # 如果不是元组，直接作为班级信息处理
                                main_window.handle_class_drop(str(class_info), row, col)
                                event.acceptProposedAction()
                                return
                        except Exception as e:
                            print(f"Error handling drag move: {e}")
                    
                    # 如果是从未安排列表拖动的
                    try:
                        class_info_str = event.mimeData().text()
                        main_window.handle_class_drop(class_info_str, row, col)
                        event.acceptProposedAction()
                        return
                    except Exception as e:
                        print(f"Error handling drop: {e}")
            
            event.ignore()
        else:
            event.ignore()
    
    def add_class_to_cell(self, row, col, class_info):
        """将班级添加到指定单元格"""
        if 0 <= row < self.rowCount() and 0 <= col < self.columnCount():
            cell = self.item(row, col)
            if cell and isinstance(cell, ScheduleCell):
                if cell.add_class(class_info):
                    self.update_cell_widgets(row, col)
                    return True
        return False
    
    def remove_class_from_cell(self, row, col, class_info):
        """从指定单元格移除班级"""
        if 0 <= row < self.rowCount() and 0 <= col < self.columnCount():
            cell = self.item(row, col)
            if cell and isinstance(cell, ScheduleCell):
                if cell.remove_class(class_info):
                    self.update_cell_widgets(row, col)
                    return True
        return False
    
    def update_cell_widgets(self, row, col):
        """更新单元格中的小部件"""
        cell = self.item(row, col)
        if not cell or not isinstance(cell, ScheduleCell):
            return
        
        # 清除现有小部件
        for widget in cell.widgets:
            widget.deleteLater()
        cell.widgets.clear()
        
        # 为每个班级创建小部件
        for class_info in cell.classes:
            class_widget = ClassCell(class_info)
            cell.widgets.append(class_widget)
            
            # 创建一个容器来放置小部件
            container = QWidget()
            layout = QVBoxLayout(container)
            layout.setContentsMargins(2, 2, 2, 2)
            layout.setSpacing(2)
            layout.addWidget(class_widget)
            
            # 设置小部件
            self.setCellWidget(row, col, container)
        
        # 如果没有班级，清除小部件
        if not cell.classes:
            self.setCellWidget(row, col, None)